package com.nulldev.util.java.swing.extSwing.eTable;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.EventObject;
import java.util.Vector;

import javax.swing.JCheckBox;
import javax.swing.JTable;
import javax.swing.event.CellEditorListener;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

import com.nulldev.util.logging.LoggerFactory;

public class eTableCheckBox extends JCheckBox implements TableCellRenderer, TableCellEditor {
	  private int selectedRow;
	  private int selectedColumn;
	  Vector<TableButtonListener> listener;
	  private String text;
	  
	  private boolean selected;
	  
	  public boolean selected() {
		  return this.selected;
	  }
	  
	  public void selected(boolean state) {
		  this.selected = state;
	  }

	  public eTableCheckBox(String text) {
	    super(text); 
	    this.text = text;
	    listener = new Vector<TableButtonListener>();
	    addActionListener(new ActionListener() { 
	      public void actionPerformed( ActionEvent e ) { 
	        for(TableButtonListener l : listener) { 
	          l.tableButtonClicked(selectedRow, selectedColumn);
	        }
	      }
	    });
	    addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				eTableCheckBox.this.selected = !eTableCheckBox.this.selected;
			}
		});
	  }

	  public eTableCheckBox() {
		LoggerFactory.getLogger().warning("-> Method shouldn't be used for actual use.");
	  }

	  public void addTableButtonListener(TableButtonListener l) {
	    listener.add(l);
	  }

	  public void removeTableButtonListener(TableButtonListener l) { 
	    listener.remove(l);
	  }

	  @Override 
	  public Component getTableCellRendererComponent(JTable table,
	    Object value, boolean isSelected, boolean hasFocus, int row, int col) {
	    return this;
	  }

	  @Override
	  public Component getTableCellEditorComponent(JTable table,
	      Object value, boolean isSelected, int row, int col) {
	    selectedRow = row;
	    selectedColumn = col;
	    return this;
	  } 

	  @Override
	  public void addCellEditorListener(CellEditorListener arg0) {      
	  } 

	  @Override
	  public void cancelCellEditing() {
	  } 

	  @Override
	  public Object getCellEditorValue() {
	    return this.text;
	  }

	  @Override
	  public boolean isCellEditable(EventObject arg0) {
	    return true;
	  }

	  @Override
	  public void removeCellEditorListener(CellEditorListener arg0) {
	  }

	  @Override
	  public boolean shouldSelectCell(EventObject arg0) {
	    return true;
	  }

	  @Override
	  public boolean stopCellEditing() {
	    return false;
	  }
}
